package com.yuanli.card.authentication.core.credentials;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by layne on 2018/5/23.
 */
public class RetryLimitCredentialsMatcher extends HashedCredentialsMatcher{
    Logger logger = LoggerFactory.getLogger(RetryLimitCredentialsMatcher.class);

    private Cache<String, AtomicInteger> passwordRetryCache;

    public RetryLimitCredentialsMatcher(Cache<String, AtomicInteger> passwordRetryCache) {
        this.passwordRetryCache = passwordRetryCache;
    }

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token,
                                      AuthenticationInfo info) {

        String username = (String) token.getPrincipal();

        AtomicInteger retryCount = passwordRetryCache.get(username);

        if (retryCount == null) {
            retryCount = new AtomicInteger(0);
            passwordRetryCache.put(username, retryCount);
        }
        logger.info("[{}]登陆系统重试次数:{}", username, retryCount);

        int i = retryCount.incrementAndGet();
        if (i > 5) throw new ExcessiveAttemptsException("账户锁定");

        passwordRetryCache.put(username, retryCount);

        boolean matches = super.doCredentialsMatch(token, info);

        if (matches) passwordRetryCache.remove(username);

        return matches;
    }
}
